package org.tulkas.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public class DispatchFilter implements Filter {
	public static final String NODISPATCH_PARAM_NAME = "noDispatch";
	public static final String TULKAS_SERVLET_PREFIX = "tulkas";
	public static final String NODISPATCH_SEPARATOR = ",";

	private String[] noDispatchPrefixes = null;

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			String ctxPath = req.getContextPath();
			String reqUri = req.getRequestURI();
			boolean noDispatch = false;
			if (noDispatchPrefixes != null) {
				for (String prefix : noDispatchPrefixes) {
					if (reqUri.startsWith(ctxPath + "/" + prefix)) {
						noDispatch = true;
						break;
					}
				}
			}

			if (noDispatch) {
				chain.doFilter(request, response);
			} else {
				RequestDispatcher rd = request.getRequestDispatcher("/"
						+ TULKAS_SERVLET_PREFIX + "/"
						+ reqUri.substring(ctxPath.length()));
				rd.forward(request, response);
			}
		}

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		String param = filterConfig.getInitParameter(NODISPATCH_PARAM_NAME);
		if (param != null) {
			noDispatchPrefixes = param.split(NODISPATCH_SEPARATOR);
		}
	}
}
